﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Windows.Markup;
using System.Collections;
using System.Windows.Navigation;
using System.Linq;
using Microsoft.Phone.Controls;
using System.Diagnostics;

namespace Odyssey.Controls
{
    [ContentProperty("Animations")]
    public sealed class PageAnimationGroup : DependencyObject
    {
        private List<PageAnimation> animations;

        public PageAnimationGroup()
            : base()
        {
        }



        /// <summary>
        /// Gets the list of PageAnimations
        /// </summary>
        public IList Animations
        {
            get { return animations ?? (animations = new List<PageAnimation>()); }
        }


        /// <summary>
        /// Gets the transition in the group which matches the specified parameters.
        /// </summary>
        /// <param name="mode">Transition mode.</param>
        /// <param name="uri">Uri to transition from or to, otherwise null.</param>
        /// <returns>Matching PageTransition, otherwise null.</returns>
        public PageAnimation GetTransition(PageAnimationMode mode, Uri uri)
        {
            List<PageAnimation> animations = this.animations;
            if (animations == null) return null;
            string original = uri != null ? uri.OriginalString : string.Empty;
            foreach (PageAnimation transition in animations)
            {
                if (IsUriMatch(original, transition.Page) && IsMatch(mode, transition.Mode)) return transition;
            }
            return animations.FirstOrDefault(t => t.Page == null && IsMatch(mode, t.Mode));
        }

        private bool IsUriMatch(string original, Uri uri)
        {
            if (uri == null)
            {
                return string.IsNullOrEmpty(original);
            }
            else
            {
                string m = uri.OriginalString;
                return original.StartsWith(m);
            }
        }


        private static bool IsMatch(PageAnimationMode a, PageAnimationMode b)
        {
            if (a == b) return true;
            if (b == PageAnimationMode.Any) return true;
            return false;
        }
    }
}
